package edu.hrbu.controller;

import com.github.pagehelper.PageInfo;
import edu.hrbu.pojo.Menu;
import edu.hrbu.pojo.Role;
import edu.hrbu.pojo.User;
import edu.hrbu.service.MenuService;
import edu.hrbu.service.RoleService;
import edu.hrbu.service.UserService;
import edu.hrbu.service.impl.MenuServiceImpl;
import edu.hrbu.service.impl.RoleServiceImpl;
import edu.hrbu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserController extends HttpServlet {

    UserService userService =  new UserServiceImpl();
    MenuService menuService = new MenuServiceImpl();
    RoleService roleService = new RoleServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String type = request.getParameter("type");
        if ("checkLogin".equals(type)) {
            doCheckLogin(request, response);
        } else if ("main".equals(type)) {
            doMain(request, response);
        } else if ("exit".equals(type)) {
            doExit(request, response);
        } else if ("checkMyName".equals(type)) {
            doCheckMyName(request, response);
        } else if ("editInfo".equals(type)) {
            doEditInfo(request, response);
        } else if ("userList".equals(type)) {
            doUserList(request, response);
        } else if ("checkName".equals(type)) {
            doCheckName(request, response);
        } else if ("addUser".equals(type)) {
            doAddUser(request, response);
        } else if ("detailUser".equals(type)) {
            doDetailUser(request, response);
        } else if ("editUser".equals(type)) {
            doEditUser(request, response);
        } else if ("delUser".equals(type)) {
            doDelUser(request, response);
        }
    }

    private void doDelUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数
        int userId = Integer.parseInt(request.getParameter("userId"));
        boolean f = userService.delUser(userId);
        if (f) {
            response.sendRedirect(request.getContextPath()+"/user?type=userList");
        }
    }

    private void doEditUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数
        int userId = Integer.parseInt(request.getParameter("userId"));
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String userTel = request.getParameter("userTel");
        String userEmail = request.getParameter("userEmail");
        int roleId = Integer.parseInt(request.getParameter("roleId"));
        Role role = roleService.getRoleByRoleId(roleId);
        User user = new User(userId, userName, userPwd, userTel, userEmail, role);
        boolean f = userService.editInfo(user);
        if (f) {
            response.sendRedirect(request.getContextPath()+"/user?type=userList");
        }
    }

    private void doDetailUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int userId = Integer.parseInt(request.getParameter("userId"));
        int roleId = Integer.parseInt(request.getParameter("roleId"));
        User user = userService.getUserById(userId, roleId);
        request.setAttribute("user", user);
        request.getRequestDispatcher("/user_edit.jsp").forward(request, response);
    }

    private void doAddUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String userTel = request.getParameter("userTel");
        String userEmail = request.getParameter("userEmail");
        int roleId = Integer.parseInt(request.getParameter("roleId"));
        Role role = roleService.getRoleByRoleId(roleId);
        User user = new User(null, userName, userPwd, userTel, userEmail, role);
        boolean f = userService.addUser(user);
        if (f) {
            response.sendRedirect(request.getContextPath()+"/user?type=userList");
        }
   }

    private void doCheckName(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数 userName
        String userName = request.getParameter("userName");
        User user = userService.checName(userName);
        response.getWriter().println(user);
    }

    private void doUserList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User loginUser = (User) request.getSession().getAttribute("loginUser");

        String pageNumStr = request.getParameter("pageNum");
        int pageNum = 1;
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        String userName = request.getParameter("userName");
        int roleId = 0;
        String roleId1 = request.getParameter("roleId");
        System.out.println("roleId1：" + roleId1);
        if (!"".equals(roleId1) && roleId1 != null) {
            roleId = Integer.parseInt(roleId1);
        }
        PageInfo<User> pageInfo = userService.getUserListPage(pageNum, loginUser.getRole().getRoleId(), userName, roleId);
        request.setAttribute("pageInfo", pageInfo);
        System.out.println("pageInfo：" + pageInfo);

        request.getRequestDispatcher("/user_list.jsp").forward(request, response);
    }

    private void doEditInfo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数 uid | uname | upwd | utel | uemail
        int uid = Integer.parseInt(request.getParameter("uid"));
        String uname = request.getParameter("uname");
        String upwd = request.getParameter("upwd");
        String utel = request.getParameter("utel");
        String uemail = request.getParameter("uemail");
        int roleId = Integer.parseInt(request.getParameter("roleId"));
        Role role = roleService.getRoleByRoleId(roleId);
        User user = new User(uid, uname, upwd, utel, uemail, role);
        boolean f = userService.editInfo(user);
        if (f) {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            if (loginUser.getUserId() == uid) { // 修改的个人信息，需退出登录
                request.getSession().removeAttribute("loginUser");
                response.sendRedirect("/login.jsp");
            } else {
                response.sendRedirect(request.getContextPath()+"/user?type=userList");
            }
        }
    }

    private void doCheckMyName(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数 uid | uname
        int uid = Integer.parseInt(request.getParameter("uid"));
        String uname = request.getParameter("uname");
        User user = userService.checkMyName(uid, uname);
        response.getWriter().println(user);
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doExit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getSession().removeAttribute("loginUser");
        response.sendRedirect("/login.jsp");
    }

    /**
     * 主界面
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doMain(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("成功");
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        List<Menu> menuList = menuService.getMenuList(loginUser.getRole().getRoleId(), 0);
//        System.out.println(menuList);
        request.setAttribute("menuList", menuList);
        List<Role> roleList = roleService.getRoleList();
        request.getSession().setAttribute("roleList", roleList);
        request.getRequestDispatcher("/main.jsp").forward(request, response);
    }

    /**
     * 登录前的校验
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doCheckLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数 uname | upwd
        String uname = request.getParameter("uname");
        String upwd = request.getParameter("upwd");
        User user = userService.checkLogin(uname, upwd);
        if (user != null) {
            request.getSession().setAttribute("loginUser", user);
        }
        System.out.println(user);
        response.getWriter().println(user);
    }
}
